package com.padgett.resourcemanagement.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.padgett.resourcemanagement.data.ClientDAO;

public final class UserRegistrationFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	/**
	 * Determine if current user is in database or not, if not, add it.
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		if(userService.isUserLoggedIn()){
			Key userKey=new KeyFactory.Builder("User",user.getEmail()).getKey();
			Entity userEntity=ClientDAO.loadEntity(userKey);
			if(userEntity==null){
				userEntity=new Entity(userKey);
				userEntity.setProperty("Email",user.getEmail());
				userEntity.setProperty("Nickname",user.getNickname());
				if(userService.isUserAdmin()){
					userEntity.setProperty("Role","admin");
				}else{
					userEntity.setProperty("Role","user");
				}
				ClientDAO.saveEntity(userEntity);
			}else{
				if(userService.isUserAdmin()){
					userEntity.setProperty("Role","admin");
				}else{
					userEntity.setProperty("Role","user");
				}
				ClientDAO.saveEntity(userEntity);
			}
			request.setAttribute("User", userEntity);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
